//实现模块的真正业务处理
const path =require('path')
const mysql = require('mysql')
const formidable = require('formidable')
const conn = mysql.createPool({
    host:'localhost',
    user:'root',
    password:'12345678',
    database:'mybase'
})
module.exports = {
    getalldata: function(req,res) {
        let sql = 'select * from heros where isdel = 0';
        conn.query(sql,(error,results) => {
            if(error) {
                res.json({
                    code:500,
                    msg:'数据查询失败,请重试'
                })
            } else {
                res.json({
                    code:200,
                    msg:'数据查询成功',
                    data:results
                })
            }
        })
    },
    uploadFile:function(req,res) {
        //创建文件上传配置
       const form = formidable();
       //配置上传文件的存放目录,绝对路径
       form.uploadDir = __dirname + '/public/images'
       //配置扩展名
       form.keepExtensions = true;
    //    实现文件上传
    form.parse(req,(err,fields,files) => {
        if(err) {
            res.json({code:500,msg:'文件上传失败'})
        } else {
            res.json({
                code:200,
                img:path.basename(files.img.path)
            })
        }
    })
    },
    add:function(req,res) {
        if(!req.body.name) {
            return res.json({code:400,msg:'name参数正确'})
        }
        let sql ='insert into heros set ?'
        conn.query(sql,req.body,(err) => {
            if(err) {
                res.json({code:500,msg:'新增失败'})
            } else {
                res.json({code:200,msg:'新增成功'})
            }
        })
    },
    getHeroById:function(req,res) {
        console.log(req.query);
        let id = req.query.id;
        //创建sql语句
        let sql = 'select * from heros where id = ' + id;

        conn.query(sql,(err,results) => {
            if(err) {
                console.log(err);
                res.json({code:500,msg:'数据查询失败'})
            } else {
                res.json({
                    code:200,
                    msg:'查询数据成功',
                    data:results[0]
                })
            }
        })
    },
    edit:function(req,res) {
         //接收参数
         console.log(req.body);
         let sql = 'update heros set ? where id = ?'
         conn.query(sql,[req.body,req.body.id],(err) => {
             if(err) {
                 console.log(err);
                 res.json({code:500,msg:'编辑失败'})
             } else {
                 res.json({code:200,msg:'编辑成功'})
             }
         })
    },
    delete:function(req,res) {
        console.log(req.query);
        // console.log(req.body);//在post请求中使用
        let sql = ' delete from heros where  id = ?'
        conn.query(sql,req.query.id,(err) => {
            if(err) {
                console.log(err);
                res.json({code:500,msg:'删除失败'})
            } else {
                res.json({code:200,msg:'删除成功'})
            }
        })
    }
       
    
}     